"""
AI配置管理器
提供动态读取和更新AI配置的功能
支持配置文件的热更新
"""

import yaml
import os
from typing import Dict, Any, Optional
from pathlib import Path
import logging
from datetime import datetime

logger = logging.getLogger(__name__)

class AIConfigManager:
    def __init__(self, config_path: str = "config/ai_config.yaml"):
        self.config_path = Path(config_path)
        self.config = {}
        self.load_config()
        
    def load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        try:
            if self.config_path.exists():
                with open(self.config_path, 'r', encoding='utf-8') as file:
                    self.config = yaml.safe_load(file) or {}
                logger.info(f"AI配置已加载: {self.config_path}")
            else:
                logger.warning(f"配置文件不存在: {self.config_path}")
                self.config = self.get_default_config()
                self.save_config()
            return self.config
        except Exception as e:
            logger.error(f"加载配置文件失败: {e}")
            self.config = self.get_default_config()
            return self.config
    
    def save_config(self) -> bool:
        """保存配置文件"""
        try:
            self.config_path.parent.mkdir(parents=True, exist_ok=True)
            with open(self.config_path, 'w', encoding='utf-8') as file:
                yaml.dump(self.config, file, allow_unicode=True, indent=2)
            logger.info(f"AI配置已保存: {self.config_path}")
            return True
        except Exception as e:
            logger.error(f"保存配置文件失败: {e}")
            return False
    
    def get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            'active_provider': 'qwen',
            'providers': {
                'qwen': {
                    'name': '通义千问',
                    'base_url': 'https://dashscope.aliyuncs.com/api/v1',
                    'api_key': 'your-qwen-api-key',
                    'models': {
                        'chat': 'qwen-max',
                        'analysis': 'qwen-plus',
                        'forecast': 'qwen-turbo'
                    },
                    'max_tokens': 2000,
                    'temperature': 0.7,
                    'timeout': 30
                },
                'glm': {
                    'name': '智谱GLM',
                    'base_url': 'https://open.bigmodel.cn/api/paas/v4',
                    'api_key': 'your-glm-api-key',
                    'models': {
                        'chat': 'glm-4',
                        'analysis': 'glm-4v',
                        'forecast': 'glm-3-turbo'
                    },
                    'max_tokens': 2000,
                    'temperature': 0.7,
                    'timeout': 30
                },
                'openai': {
                    'name': 'OpenAI',
                    'base_url': 'https://api.openai.com/v1',
                    'api_key': 'your-openai-api-key',
                    'models': {
                        'chat': 'gpt-4',
                        'analysis': 'gpt-3.5-turbo',
                        'forecast': 'gpt-3.5-turbo'
                    },
                    'max_tokens': 2000,
                    'temperature': 0.7,
                    'timeout': 30
                }
            },
            'ai_functions': {
                'demand_forecast': {
                    'provider': 'qwen',
                    'model': 'forecast',
                    'system_prompt': '你是一个供应链需求预测专家，请基于提供的数据进行准确的预测分析。'
                },
                'anomaly_detection': {
                    'provider': 'qwen',
                    'model': 'analysis',
                    'system_prompt': '你是一个供应链异常检测专家，请识别数据中的异常模式并提供解决方案。'
                },
                'supplier_analysis': {
                    'provider': 'qwen',
                    'model': 'analysis',
                    'system_prompt': '你是一个供应商管理专家，请分析供应商表现并提供改进建议。'
                },
                'inventory_optimization': {
                    'provider': 'qwen',
                    'model': 'analysis',
                    'system_prompt': '你是一个库存管理专家，请提供最优的库存策略建议。'
                }
            },
            'cache': {
                'enabled': True,
                'ttl': 1800,  # 30分钟
                'max_size': 1000
            },
            'rate_limit': {
                'enabled': True,
                'requests_per_minute': 60,
                'requests_per_hour': 1000
            },
            'monitoring': {
                'enabled': True,
                'log_file': 'logs/ai_usage.log',
                'metrics_file': 'logs/ai_metrics.json'
            }
        }
    
    def get_provider_config(self, provider: str) -> Optional[Dict[str, Any]]:
        """获取特定提供商配置"""
        return self.config.get('providers', {}).get(provider)
    
    def get_active_provider(self) -> str:
        """获取当前激活的提供商"""
        return self.config.get('active_provider', 'qwen')
    
    def set_active_provider(self, provider: str) -> bool:
        """设置激活的提供商"""
        if provider in self.config.get('providers', {}):
            self.config['active_provider'] = provider
            return self.save_config()
        return False
    
    def update_provider_config(self, provider: str, config: Dict[str, Any]) -> bool:
        """更新提供商配置"""
        if 'providers' not in self.config:
            self.config['providers'] = {}
        
        if provider not in self.config['providers']:
            self.config['providers'][provider] = {}
        
        self.config['providers'][provider].update(config)
        return self.save_config()
    
    def add_provider(self, provider: str, config: Dict[str, Any]) -> bool:
        """添加新的提供商"""
        if 'providers' not in self.config:
            self.config['providers'] = {}
        
        self.config['providers'][provider] = config
        return self.save_config()
    
    def remove_provider(self, provider: str) -> bool:
        """移除提供商"""
        providers = self.config.get('providers', {})
        if provider in providers:
            del providers[provider]
            
            # 如果移除的是当前激活的提供商，切换到第一个可用的
            if self.config.get('active_provider') == provider:
                available_providers = list(providers.keys())
                if available_providers:
                    self.config['active_provider'] = available_providers[0]
                else:
                    self.config['active_provider'] = 'qwen'
            
            return self.save_config()
        return False
    
    def get_function_config(self, function: str) -> Optional[Dict[str, Any]]:
        """获取特定AI功能配置"""
        return self.config.get('ai_functions', {}).get(function)
    
    def update_function_config(self, function: str, config: Dict[str, Any]) -> bool:
        """更新AI功能配置"""
        if 'ai_functions' not in self.config:
            self.config['ai_functions'] = {}
        
        self.config['ai_functions'][function] = config
        return self.save_config()
    
    def get_cache_config(self) -> Dict[str, Any]:
        """获取缓存配置"""
        return self.config.get('cache', {})
    
    def get_rate_limit_config(self) -> Dict[str, Any]:
        """获取限流配置"""
        return self.config.get('rate_limit', {})
    
    def get_monitoring_config(self) -> Dict[str, Any]:
        """获取监控配置"""
        return self.config.get('monitoring', {})
    
    def validate_config(self) -> Dict[str, Any]:
        """验证配置有效性"""
        errors = []
        warnings = []
        
        # 检查激活的提供商
        active_provider = self.get_active_provider()
        if active_provider not in self.config.get('providers', {}):
            errors.append(f"激活的提供商 '{active_provider}' 不存在")
        
        # 检查提供商配置
        for provider, config in self.config.get('providers', {}).items():
            if not config.get('api_key') or config.get('api_key') == 'your-api-key':
                warnings.append(f"提供商 '{provider}' 的API密钥未设置")
            
            if not config.get('base_url'):
                errors.append(f"提供商 '{provider}' 的base_url未设置")
        
        # 检查AI功能配置
        for function, config in self.config.get('ai_functions', {}).items():
            provider = config.get('provider')
            if provider and provider not in self.config.get('providers', {}):
                errors.append(f"功能 '{function}' 指定的提供商 '{provider}' 不存在")
        
        return {
            'valid': len(errors) == 0,
            'errors': errors,
            'warnings': warnings
        }
    
    def export_config(self, file_path: str) -> bool:
        """导出配置到文件"""
        try:
            export_data = {
                'exported_at': datetime.now().isoformat(),
                'config': self.config,
                'metadata': {
                    'version': '1.0.0',
                    'format': 'ai_config_v1'
                }
            }
            
            with open(file_path, 'w', encoding='utf-8') as file:
                yaml.dump(export_data, file, allow_unicode=True, indent=2)
            
            return True
        except Exception as e:
            logger.error(f"导出配置失败: {e}")
            return False
    
    def import_config(self, file_path: str) -> bool:
        """从文件导入配置"""
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                data = yaml.safe_load(file)
            
            if isinstance(data, dict) and 'config' in data:
                self.config = data['config']
            else:
                self.config = data
            
            return self.save_config()
        except Exception as e:
            logger.error(f"导入配置失败: {e}")
            return False
    
    def get_config_summary(self) -> Dict[str, Any]:
        """获取配置摘要"""
        providers = self.config.get('providers', {})
        functions = self.config.get('ai_functions', {})
        
        return {
            'active_provider': self.get_active_provider(),
            'total_providers': len(providers),
            'available_providers': [p for p in providers.keys()],
            'total_functions': len(functions),
            'functions': list(functions.keys()),
            'cache_enabled': self.get_cache_config().get('enabled', False),
            'rate_limit_enabled': self.get_rate_limit_config().get('enabled', False)
        }

# 全局配置管理器实例
config_manager = AIConfigManager()

# 便捷函数
def get_ai_config():
    """获取当前AI配置"""
    return config_manager.config

def switch_ai_provider(provider: str) -> bool:
    """切换AI提供商"""
    return config_manager.set_active_provider(provider)

def update_api_key(provider: str, api_key: str) -> bool:
    """更新API密钥"""
    return config_manager.update_provider_config(provider, {'api_key': api_key})

def add_custom_provider(name: str, config: Dict[str, Any]) -> bool:
    """添加自定义提供商"""
    return config_manager.add_provider(name, config)

if __name__ == "__main__":
    # 测试配置管理器
    print("AI配置管理器测试")
    print("=" * 50)
    
    # 显示当前配置摘要
    summary = config_manager.get_config_summary()
    print("配置摘要:")
    for key, value in summary.items():
        print(f"  {key}: {value}")
    
    # 验证配置
    validation = config_manager.validate_config()
    print("\n配置验证:")
    print(f"  有效: {validation['valid']}")
    if validation['errors']:
        print("  错误:")
        for error in validation['errors']:
            print(f"    - {error}")
    if validation['warnings']:
        print("  警告:")
        for warning in validation['warnings']:
            print(f"    - {warning}")